<template>
  <div id="purchaseOrders">
    <search-form
      ref="search"
      :type="2"
      @handleSearch="handleSearch"
    ></search-form>
    <div class="table-main">
      <div class="empty-header" v-show="activeHeader"></div>
      <div class="table-header" :class="[activeHeader ? 'active-header' : '']">
        <span class="title"></span>
        <div class="action-bar">
          <el-upload
          v-show="showBtn"
            class="upload-demo"
            :action="uploadUrl"
            multiple
            :show-file-list="false"
            :on-success="handleSuccess"
            :on-error="handleError"
          >
            <el-button size="mini" plain>导入创建补差价</el-button>
          </el-upload>
          <el-button size="mini" v-show="showBtn" plain @click="handleExport"
            >导出明细</el-button
          >
        </div>
      </div>
      <el-table
        :data="tableData"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
        border
        :header-cell-style="{
          color: '#333',
          fontSize: '12px',
          background: '#eee',
          fontWeight: '700'
        }"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column
          v-for="(item, index) in headers"
          :label="item.label"
          :fixed="item.fixed"
          :key="index"
          :width="item.width"
        >
          <template slot-scope="scope">
            <template
              v-if="'createTime,predictArrivedTime,appointmentDate'.includes(item.prop)"
            >
              <span>{{
                common.dateFmt(scope.row[item.prop], "yyyy-MM-dd hh:mm:ss",1)
              }}</span>
            </template>
            <template v-else-if="'deliveryBatch'.includes(item.prop)">
              <el-link
                :underline="false"
                type="primary"
                @click="
                  $router.push({
                    path: '/warehouseDetails',
                    query: { ...scope.row }
                  })
                "
              >
                {{ scope.row[item.prop] }}
              </el-link>
            </template>
            <template v-else-if="'purchaseNo'.includes(item.prop)">
              <span>{{ scope.row[item.prop] }}</span>
              <p>经营模式：{{ scope.row["operationMode"] }}</p>
              <p>单据类型：{{ scope.row["orderType"] }}</p>
            </template>
            <template v-else-if="'channelName'.includes(item.prop)">
              <p>来源类型：补货越库</p>
              <p>来源单号：{{ scope.row["channelId"] }}</p>
              <p>合同编号：158098</p>
            </template>
            <template v-else-if="'providerName'.includes(item.prop)">
              <p>{{ scope.row[item.prop] }}</p>
              <p>{{ scope.row["providerNo"] }}</p>
            </template>
            <template v-else-if="'deliveryAmount'.includes(item.prop)">
              <p>币种：CNY(人民币)</p>
              <p>金额：{{ scope.row[item.prop] }}.00</p>
            </template>
            <template v-else-if="'stockName'.includes(item.prop)">
              <p>{{ scope.row[item.prop] }}</p>
              <p>{{ scope.row['stockNo'] }}</p>
            </template>
            <template v-else-if="'deliveryQuantity'.includes(item.prop)">
              <p>SKU个数：{{ scope.row["skuCount"] }}</p>
              <p>实发数量：{{ scope.row["deliveryQuantity"] }}</p>
              <p>到货数量：{{ scope.row["quantity11"] }}</p>
            </template>
            <template v-else>
              <span>{{ scope.row[item.prop] }}</span>
            </template>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="状态/审核人" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.deliveryStatus }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="80">
          <template slot-scope="scope">
            <el-link
              :underline="false"
              type="success"
              @click="
                $router.push({
                  path: '/warehouseDetails',
                  query: { ...scope.row }
                })
              "
              style="font-size:12px;">详情</el-link
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="bottom-page">
        <div class="scroll-table-wrapper">
          <div class="scrollbar-inner" :style="{width:scrollBarWidth}"></div>
        </div>
        <Pagination
          :total="total"
          :pageData="page"
          @handlePageChange="handlePageChange"
        ></Pagination>
      </div>
    </div>
  </div>
</template>

<script>
import SearchForm from "@/components/SearchForm/";
import { headers } from "./config";
const page = () => {
  return {
    page: 1,
    size: 10,
    
  };
};
export default {
  name:'warehouseWarrant',
  components: { SearchForm },
  data() {
    return {
      page: page(),
      total: 0, // 总条数
      tableData: [],
      headers,
      selections: [],
      form: {},
      uploadUrl: `/api/stock-ins/excel`,
      activeHeader:false,
      distance_header:0,
      scrollBarWidth:'2000px',
      wareScrolled:0
    };
  },
  created() {
    this.init();
  },
  mounted() {
    // 一次性计算赋值，减少滚动计算节点位置次数
    let header = document.querySelector(".table-header")
    let par = document.querySelector(".table-header").offsetParent
    if(par.nodeName.toLowerCase() == "body") {
      this.distance_header = header.offsetTop
    } else {
      while(par) {
        this.distance_header += par.offsetTop
        par = par.offsetParent
      }
    }
    if(this.distance_header != 0) {
      this.distance_header -= 72
    }
    this.$nextTick(function() {
      document
        .querySelector("#purchaseOrders")
        .addEventListener("scroll", this.onScroll);
        document
        .querySelector(".scroll-table-wrapper")
        .addEventListener("scroll", this.setLeft);
        const ele = document.querySelector(".el-table__body")
        this.scrollBarWidth = window.getComputedStyle(ele).width
    });
    window.addEventListener("scroll", this.onScroll, true);
  },
  watch:{
      activeHeader:function(newVal,oldVal){
         this.setTop(newVal)
      }
  },
  computed:{
    showBtn(){
      return this.$store.state.app.showBtn
    }
  },
  activated() {
    this.onScroll(this.wareScrolled)
  },
  methods: {
    setLeft(){
      const scrollLeft = document.querySelector(".scroll-table-wrapper").scrollLeft
      document.querySelector(".el-table__body-wrapper").scrollLeft = scrollLeft
      console.log(scrollLeft, 'scrollLeft')
    },
    setTop(val){
      if(this.$route.name == "warehouseWarrant") {
        var adom = document.querySelector('.el-table__header-wrapper');
        var adom1 = document.querySelector('.el-table__fixed .el-table__fixed-header-wrapper'); //左边
        var adom1Body = document.querySelector('.el-table__fixed .el-table__fixed-body-wrapper');

        var adom2 = document.querySelector('.el-table__fixed-right .el-table__fixed-header-wrapper');
        var adom2Body = document.querySelector('.el-table__fixed-right .el-table__fixed-body-wrapper');

        var wid = document.querySelector('.el-table__fixed-header-wrapper').offsetWidth-200;
        var adom2header = document.querySelector('.el-table__fixed-right .el-table__header');
        if(val){
          adom.classList.add("bpositiheader2");
          adom1.classList.add("bpositiheader");
          adom1Body.classList.add("bpositiheader2body");
          adom2.classList.add("bpositiheader3");
          adom2Body.classList.add("bpositiheader2body");
          adom2header.style.marginLeft = -wid + 'px'
        }else{
          adom.classList.remove("bpositiheader2");
          adom1Body.classList.remove("bpositiheader2body");
          adom1.classList.remove("bpositiheader");
          adom2.classList.remove("bpositiheader3");
          adom2Body.classList.remove("bpositiheader2body");
          adom2header.style.marginLeft = 0 + 'px'
        }
      }
    },
    // 查询按钮事件
    handleSearch(form) {
      this.page = page();
      this.form = form;
      this.init();
    },
    handlePageChange(pages) {
      this.page = pages;
      this.init();
    },
    // 列表多选
    handleSelectionChange(element) {
      this.selections = element;
    },
    init() {
      const params = {
        size: this.page.size,
        page: this.page.page <= 0 ? 0 : this.page.page - 1,
        ...this.form,
        sort:"id"
      };
      this.$http("/stock-ins", params).then(res => {
        this.tableData = res.records ? res.records : [];
        this.total = isNaN(res.totalElements) ? 0 : Number(res.totalElements);
      });
    },
    // 导出
    handleExport() {
      const params = {
        ...this.page,
        page:this.page.page - 1
      };
      window.open(
        "http://web.tmall.pingyee.com.cn/" +
          "/stock-ins/excel?" +
          this.common.createUrl(params)
      );
    },
     onScroll(aliveScroll) {
      if(this.$route.name == "warehouseWarrant") {
        if(aliveScroll && !isNaN(aliveScroll)) {
          console.log(aliveScroll)
          document.querySelector(".app-wrapper").scrollTop = aliveScroll
        }
        const scrolled = document.querySelector(".app-wrapper").scrollTop;
        this.wareScrolled = scrolled
        if (scrolled >= 258) {
          this.activeHeader = true
        } else {
          this.activeHeader = false
        }
      }
    },
    // 导入后 成功&失败 回调
    handleSuccess(res) {
      this.$message({
        message: "导入成功！",
        type: "success",
        offset: 100
      });
    },
    handleError(err) {
      this.$message({
        message: "导入失败！",
        type: "error",
        offset: 100
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.table-main {
  margin: 12px;
  background-color: #fff;
  padding-bottom: 45px;
  .upload-demo {
    display: inline-block;
  }
  .table-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 50px;
    padding: 0 10px;
    .title {
      font-size: 16px;
    }
  }
  .scroll-table-wrapper {
    overflow-x: auto;
    overflow-y: hidden;
    bottom: 0;
    z-index: 1; 
    display: block;
    margin-top: -18px;
    .scrollbar-inner {
      height: 1px;
      visibility: hidden;
    }
  }
  .bottom-page {
    position: fixed;
    bottom: 0;
    background-color: #fff;
    z-index: 200;
    left: 196px;
    right: 29px;
  }
}
</style>

<style scoped>
.table-main >>> .el-table__body,
.table-main >>> .el-table__body p {
  font-size: 12px;
}
 .active-header {
    position: fixed;
    top:72px;
    left: 194px;
    right: 29px;
    background-color: #fff;
    z-index: 200;
  }
.table-main >>> .el-table .cell {
  line-height: 14px;
}
.table-main >>> .el-table td,
.table-main >>> .el-table th {
  padding: 8px 0;
}
</style>
